<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="listQuery.search.tid" placeholder="京东/有赞订单编号" style="width: 150px;" class="filter-item" />
      <el-input v-model="listQuery.search.goodsName" placeholder="商品名称" style="width: 150px;" class="filter-item" />
      <el-input v-model="listQuery.search.skuProperty" placeholder="商品规格" style="width: 150px;" class="filter-item" />
      <el-input v-model="listQuery.search.receiverName" placeholder="收货人" style="width: 150px;" class="filter-item" />
      <el-input v-model="listQuery.search.tradeRemark" placeholder="卖家备注" style="width: 150px;" class="filter-item" />
      <el-select v-model="listQuery.search.state" placeholder="订单状态" clearable style="width: 150px" class="filter-item">
        <el-option v-for="item in orderStateOptions" :key="item.name" :label="item.name" :value="item.value" />
      </el-select>
      <el-date-picker
        v-model="listQuery.search.dateStr"
        style="width: 400px;"
        type="datetimerange"
        value-format="yyyy-MM-dd HH:mm:ss"
        range-separator="至"
        start-placeholder="开始时间"
        end-placeholder="结束时间"
        class="filter-item"
      />
      <el-button v-waves class="filter-item" type="default" icon="el-icon-search" @click="handleFilter">
        搜索
      </el-button>
      <el-button
        class="filter-item"
        style="margin-left: 10px;"
        type="primary"
        @click="handleYZ"
      >
        获取有赞订单
      </el-button>
      <el-button
        class="filter-item"
        style="margin-left: 10px;"
        type="primary"
        @click="handleJD"
      >
        获取京东订单
      </el-button>
      <el-button
        class="filter-item"
        style="margin-left: 10px;"
        type="success"
        @click="handleBatchDelivery"
      >
        批量发货
      </el-button>
      <el-button
        class="filter-item"
        style="margin-left: 10px;"
        type="danger"
        @click="handleBatchDelete"
      >
        批量删除
      </el-button>
      <el-button
        class="filter-item"
        style="margin-left: 10px;"
        type="warning"
        @click="handleJDAuth"
      >
        京东授权
      </el-button>
    </div>
    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      @selection-change="handleSelectionChange"
    >
      <el-table-column
        type="selection"
        width="55"
      />
      <el-table-column label="京东编号" align="center" min-width="7%">
        <template slot-scope="scope">
          <span>{{ scope.row.jdId }}</span>
        </template>
      </el-table-column>
      <el-table-column label="有赞订单编号" min-width="10%" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.yzId }}</span>
        </template>
      </el-table-column>
      <el-table-column label="商品名称" min-width="10%">
        <template slot-scope="scope">
          <span>{{ scope.row.goodsName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="商品规格" min-width="10%" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.skuProperty }}</span>
        </template>
      </el-table-column>
      <el-table-column label="收货人" min-width="5%" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.receiverName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="收货人手机号" min-width="7%" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.receiverTel }}</span>
        </template>
      </el-table-column>
      <el-table-column label="收货地址" min-width="13%" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.deliveryAddress }}</span>
        </template>
      </el-table-column>
      <el-table-column label="下单时间" min-width="10%" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.bookTime }}</span>
        </template>
      </el-table-column>
      <el-table-column min-width="10%" label="卖家备注">
        <template slot-scope="{row}">
          <template v-if="row.edit">
            <el-input v-model="row.tradeRemark" class="edit-input" size="small" />
            <el-button
              class="cancel-btn"
              size="small"
              type="info"
              style="margin-top: 3px;"
              @click="cancelEdit(row)"
            >
              取消
            </el-button>
          </template>
          <span v-else>{{ row.tradeRemark }}</span>
        </template>
      </el-table-column>
      <el-table-column label="订单状态" class-name="status-col" min-width="5%">
        <template slot-scope="{row}">
          <span>{{ row.state | orderStateFilter }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" min-width="7%" class-name="small-padding fixed-width">
        <template slot-scope="{row}">
          <el-button
            v-if="row.state === 1"
            size="mini"
            type="success"
            style="margin: 3px 2px;"
            @click="handleDelivery(row)"
          >发货
          </el-button>
          <el-button
            v-if="row.edit"
            type="warning"
            size="mini"
            style="margin: 3px 2px;"
            @click="confirmEdit(row)"
          >确定
          </el-button>
          <el-button
            v-else
            type="primary"
            size="mini"
            style="margin: 3px 2px;"
            @click="row.edit=!row.edit"
          >备注
          </el-button>
          <el-button
            size="mini"
            type="danger"
            style="margin: 3px 2px;"
            @click="handleDelete(row)"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="listQuery.curPage"
      :limit.sync="listQuery.pageSize"
      @pagination="getList"
    />

    <el-dialog
      :title="dialog.title"
      :visible.sync="dialog.visible"
      width="30%"
      :show-close.sync="dialog.showClose"
      :close-on-click-modal="dialog.closeOnClick"
      :close-on-press-escape="dialog.closeOnPress"
      @close="handleDialogClose"
    >
      <el-progress :percentage="dialog.percentage" />
      <br>
      <span>共 {{ dialog.total }} 条</span>
      <span>已完成 {{ dialog.success }} 条</span>
      <span>重复记录 {{ dialog.failed }} 条</span>
    </el-dialog>
  </div>
</template>

<script>
import { listPage, getYZ, getJd, deleteOrder, batchDeleteOrder, getProgress, jdAuthGetCode, batchDelivery, updateRemark } from '@/api/delivery'
import waves from '@/directive/waves' // waves directive
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
const orderStateOptions = [
  { name: '全部', value: '' },
  { name: '初始化', value: 0 },
  { name: '待发货', value: 1 },
  { name: '已发货', value: 2 }
]

const orderStateOptionsKeyValue = orderStateOptions.reduce((acc, cur) => {
  acc[cur.value] = cur.name
  return acc
}, {})

export default {
  name: 'Delivery',
  components: { Pagination },
  directives: { waves },
  filters: {
    orderStateFilter(state) {
      return orderStateOptionsKeyValue[state]
    }
  },
  data() {
    return {
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        curPage: 1,
        pageSize: 10,
        search: {
          tid: '',
          goodsName: '',
          receiverName: '',
          state: '',
          dateStr: '',
          skuProperty: '',
          tradeRemark: ''
        }
      },
      orderStateOptions,
      dialog: {
        title: '',
        visible: false,
        showClose: false,
        closeOnClick: false,
        closeOnPress: false,
        total: 0,
        success: 0,
        failed: 0,
        percentage: 0
      },
      multipleSelection: []
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      this.listLoading = true
      const requestData = {
        curPage: this.listQuery.curPage,
        pageSize: this.listQuery.pageSize,
        searchValue: JSON.stringify(this.listQuery.search)
      }
      listPage(requestData).then(response => {
        this.listLoading = false
        const items = response.data.list
        this.list = items.map(v => {
          this.$set(v, 'edit', false) // https://vuejs.org/v2/guide/reactivity.html
          v.originalRemark = v.tradeRemark //  will be used when user click the cancel botton
          return v
        })
        this.total = response.data.total
      })
    },
    handleFilter() {
      this.listQuery.curPage = 1
      this.getList()
    },
    handleYZ() {
      this.$confirm('是否确认同步有赞订单信息?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        getYZ().then(response => {
          this.dialog.visible = true
          this.dialog.title = '获取有赞订单提示'
          // 定义定时器开始时间为0
          const timer = setInterval(() => {
            getProgress(response.data).then(resp => {
              const data = resp.data
              if (data) {
                this.dialog.total = data.total
                this.dialog.success = data.success
                this.dialog.failed = data.failed
                this.dialog.percentage = parseInt((data.success + data.failed) * 100 / data.total)
              }
            })
            if (this.dialog.percentage >= 100) {
              this.dialog.showClose = true
              clearInterval(timer)
            }
          }, 1000)
        })
      }).catch(() => {
        this.$message({
          type: 'warning',
          message: '已取消同步有赞订单信息'
        })
      })
    },
    handleJD() {
      this.$confirm('是否确认同步京东订单信息?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        getJd().then(response => {
          this.dialog.visible = true
          this.dialog.title = '获取京东订单提示'
          // 定义定时器开始时间为0
          const timer = setInterval(() => {
            getProgress(response.data).then(resp => {
              const data = resp.data
              if (data) {
                this.dialog.total = data.total
                this.dialog.success = data.success
                this.dialog.failed = data.failed
                this.dialog.percentage = parseInt((data.success + data.failed) * 100 / data.total)
              }
            })
            if (this.dialog.percentage >= 100) {
              this.dialog.showClose = true
              clearInterval(timer)
            }
          }, 1000)
        })
      }).catch(() => {
        this.$message({
          type: 'warning',
          message: '已取消同步京东订单信息'
        })
      })
    },
    handleBatchDelivery() {
      this.$confirm('是否确认发送全部选中的订单信息?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        if (this.multipleSelection.length <= 0) {
          this.$message({
            type: 'warning',
            message: '请先选择要发送的记录!'
          })
          return
        }
        const arr = []
        this.multipleSelection.forEach(item => {
          arr.push(item.id)
        })
        batchDelivery(arr).then(response => {
          this.$message({
            type: 'success',
            message: '发送成功!'
          })
          this.handleFilter()
        })
      }).catch(() => {
        this.$message({
          type: 'warning',
          message: '已取消发送'
        })
      })
    },
    handleBatchDelete() {
      this.$confirm('是否确认删除全部选中的订单信息?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        if (this.multipleSelection.length <= 0) {
          this.$message({
            type: 'warning',
            message: '请先选择要删除的记录!'
          })
          return
        }
        const arr = []
        this.multipleSelection.forEach(item => {
          arr.push(item.id)
        })
        batchDeleteOrder(arr).then(response => {
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
          this.handleFilter()
        })
      }).catch(() => {
        this.$message({
          type: 'warning',
          message: '已取消删除'
        })
      })
    },
    handleJDAuth() {
      jdAuthGetCode().then(response => {
        // window.location.href = response.data
        window.open(response.data, '_blank')
      })
    },
    handleDelete(row) {
      this.$confirm('是否确认删除订单信息?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteOrder(row.id).then(response => {
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
          this.handleFilter()
        })
      }).catch(() => {
        this.$message({
          type: 'warning',
          message: '已取消删除'
        })
      })
    },
    handleDelivery(row) {
      this.$confirm('是否确认发货?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const arr = []
        arr.push(row.id)
        batchDelivery(arr).then(response => {
          this.$message({
            type: 'success',
            message: '发货成功'
          })
          this.handleFilter()
        })
      }).catch(() => {
        this.$message({
          type: 'warning',
          message: '已取消发货'
        })
      })
    },
    cancelEdit(row) {
      row.tradeRemark = row.originalRemark
      row.edit = false
      this.$message({
        message: '取消对卖家备注的编辑',
        type: 'warning'
      })
    },
    confirmEdit(row) {
      this.$confirm('是否确认更新有赞订单卖家备注信息?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        updateRemark(row.id, row.tradeRemark).then(response => {
          // row.edit = false
          // row.originalRemark = row.tradeRemark
          this.$message({
            message: '卖家备注更新成功',
            type: 'success'
          })
          this.handleFilter()
        })
      }).catch(() => {
        this.$message({
          type: 'warning',
          message: '取消对卖家备注的编辑'
        })
        row.tradeRemark = row.originalRemark
        row.edit = false
      })
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    handleDialogClose() {
      this.dialog.visible = false
      this.dialog.title = ''
      this.dialog.showClose = false
      this.dialog.total = 0
      this.dialog.success = 0
      this.dialog.failed = 0
      this.dialog.percentage = 0
      this.handleFilter()
    }

  }
}
</script>
